package escuela.tpfinal.cotizadorTPS.cliente;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value="/cliente")
public class ClienteController {
	
	@Autowired
	private ClienteRepository clienteRepository;

	@RequestMapping(value="/listar")
	public void listar(ModelMap modelMap, @RequestParam(value="filtroNombre", required=false) String filtroNombre) {
		List<Cliente> clientes = clienteRepository.findLikeNombre(filtroNombre);
		System.out.println("hay clientes " + clientes.size());
		modelMap.addAttribute("listaCliente", clientes);
	}
	
	@RequestMapping(value="/crear")
	public ClienteForm crear() {
		System.out.println("crear GET");
		return new ClienteForm();
	}

	@RequestMapping(value="/crear", method = RequestMethod.POST)
	public String crear(@ModelAttribute ClienteForm clienteForm) {
		System.out.println("crear POST");
		clienteRepository.save(clienteForm.createCliente());
		return "redirect:/cliente/listar";
	}

	@RequestMapping(value="/editar")
	public ClienteForm editar(@RequestParam(value="id") Long id) {
		System.out.println("editar GET");
		Cliente cliente = clienteRepository.findById(id);
		ClienteForm clienteForm = ClienteForm.newFrom(cliente);
		return clienteForm;
	}

	@RequestMapping(value="/editar", method = RequestMethod.POST)
	public String editar(@ModelAttribute ClienteForm clienteForm) {
		try {
			System.out.println("crear POST");
			Cliente cliente = clienteRepository.findById(clienteForm.getId());
			clienteRepository.update(cliente);
			clienteForm.actualizarCliente(cliente);
			clienteRepository.update(cliente);
			return "redirect:/cliente/listar";
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

	@RequestMapping(value="/eliminar", method = RequestMethod.POST)
	public String eliminar(@RequestParam(value="id") Long id) {
		try {
			System.out.println("delete POST " + id);
			clienteRepository.deleteById(id);
			return "redirect:/cliente/listar";
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

}
